package com.bayern.muchen.more_test.ordertest;

import com.bayern.muchen.more_test.ordertest.mapper.OrderMapper;
import com.bayern.muchen.more_test.ordertest.pojo.OrderEntity;
import com.bayern.muchen.more_test.ordertest.pojo.OrderRespVo;
import com.bayern.muchen.more_test.ordertest.pojo.OrderVo;
import com.bayern.muchen.more_test.ordertest.pojo.WareEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.UUID;

/**
 * @author QIUYANG
 * @title: OrderService
 * @description: TODO
 * @date 2022/1/1414:59
 */
@Service
public class OrderService {


    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    OrderMapper orderMapper;


    /**
     * 下单
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public OrderRespVo submitOrder(OrderVo orderVo) {
        OrderRespVo respVo = new OrderRespVo();
        //1、验证令牌[对比和删除必须保证原子性]
//        String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEY[1]) else return 0 end";
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        Long execute = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("order:token:qiuyang"), orderVo.getToken());
//        if (execute == 0L) {
//            respVo.setCode(-1);
//            return respVo;
//        }
        //3、验价格

        //2、锁定库存
        lockWare();
        //3、创建订单
        createOrder();

        respVo.setCode(0);
        respVo.setMsg(orderMapper.selectAll());
        return respVo;
    }

    /**
     * 锁定库存
     */
    @Transactional(rollbackFor = Exception.class)
    public void lockWare() {
        WareEntity wareEntity = new WareEntity();
        wareEntity.setId(1);
        wareEntity.setWlock(2);
        int i = orderMapper.lockWare(wareEntity);
        if (i == 0) {
            throw new NoStockException();
        }
    }

    /**
     * 创建订单
     */
    private void createOrder() {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderStatus("1");
        orderEntity.setOrderId(UUID.randomUUID().toString().replace("-", ""));
        orderMapper.insert(orderEntity);
    }


}
